/**
 * 应用启动模块
 */
let isUtilsLoaded = false
let startModule = {
    bootGame: 1,
    agreeProtocol: 2,
    updateResources: 3,
    updateRevision: 4,
    skipNotice: 5,
    quickGame: 6,
    realNameAuthentication: 7,
    startGame: 8,
    createUserAvatar: 9
}
let utils = {autoJSUtil: null, gestureUtil: null}

function main() {
    // 判断当前是否在战斗中
    console.warn('应用启动模块执行...')
    if (!isUtilsLoaded) {
        loadUtils()
        isUtilsLoaded = true
    }
    const store = storages.create('applicationStartModule')
    const state = nowState(store)
    switch (state.state) {
        case startModule.bootGame:
            bootGame(state.pos);
            break;
        case startModule.agreeProtocol:
            agreeProtocol();
            break;
        case startModule.updateResources:
            updateResources();
            break;
        case startModule.updateRevision:
            updateResvision();
            break;
        case startModule.skipNotice:
            skipNotice();
            break;
        case startModule.quickGame:
            quickGame(state.pos);
            break;
        case startModule.realNameAuthentication:
            realNameAuthentication()
            break;
        case startModule.startGame:
            startGame(state.pos)
            break;
        case startModule.createUserAvatar:
            createUserAvatar(state.pos);
            break
    }
}

function loadUtils() {
    const configStorage = storages.create('config')
    utils.autoJSUtil = eval(configStorage.get('autoJSUtil'))
    utils.gestureUtil = eval(configStorage.get('gestureUtil'))
    utils.imageUtil = eval(configStorage.get('imageUtil'))
    utils.fileUtil = eval(configStorage.get('fileUtil'))
}

/**
 * 点击偏移位置
 */
function clickPos(pos) {
    click(pos.x + 5, pos.y + 5)
}

function nowState(store) {
    let state = 0
    let pos = {x: 0, y: 0}

    const source = utils.imageUtil.captureCurrentScreen()

    if (isStateNotExc(store, startModule.bootGame)) {
        const startIconPos = utils.imageUtil.findTemplateImgInSource(source, 'common/mz_logo.png')
        if (startIconPos) {
            state = startModule.bootGame
            pos = startIconPos
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.agreeProtocol)) {
        const agreeProtocol = utils.imageUtil.findTemplateImgInSource(source, 'login/agree_protocol.png')
        if (agreeProtocol) {
            state = startModule.agreeProtocol
            pos = agreeProtocol
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.updateResources)) {
        const updateResources = utils.imageUtil.findTemplateImgInSource(source, 'login/update_resources.png')
        if (updateResources) {
            state = startModule.updateResources
            pos = updateResources
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.updateRevision)) {
        const updateRevision = utils.imageUtil.findTemplateImgInSource(source, 'login/update_revision.png')
        if (updateRevision) {
            state = startModule.updateRevision
            pos = updateRevision
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.skipNotice)) {
        const notice = utils.imageUtil.findTemplateImgInSource(source, 'login/notice.png')
        if (notice) {
            state = startModule.skipNotice
            pos = notice
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.quickGame)) {
        const quickGame = utils.imageUtil.findTemplateImgInSource(source, 'login/quick_game.png')
        if (quickGame) {
            state = startModule.quickGame
            pos = quickGame
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.realNameAuthentication)) {
        const realNameAuth = utils.imageUtil.findTemplateImgInSource(source, 'login/real_name_auth.png')
        if (realNameAuth) {
            state = startModule.realNameAuthentication
            pos = realNameAuth
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.startGame)) {
        const changeArea = utils.imageUtil.findTemplateImgInSource(source, 'login/change_area.png')
        if (changeArea) {
            state = startModule.startGame
            pos = changeArea
            addState(store, state)
        }
    }

    if (isStateNotExc(store, startModule.createUserAvatar)) {
        const createUserAvatar = utils.imageUtil.findTemplateImgInSource(source, 'login/create_user_avatar.png')
        if (createUserAvatar) {
            state = startModule.createUserAvatar
            pos = createUserAvatar
            addState(store, state)
        }
    }

    return {
        pos,
        state
    }
}

function bootGame(startIconPos) {
    if (launch('com.zlongame.mhmnz')) {
        console.log('通过包启动成功')
    } else if (launchApp('梦幻模拟战')) {
        console.log('通过应用名启动成功')
    } else {
        // 都失败, 最后直接点击图标位置, 进行启动
        clickPos(startIconPos)
    }
}

function agreeProtocol() {
    const agree = utils.imageUtil.findImageInCapture('login/agree.png')
    if (agree) {
        clickPos(agree)
    }
}

function updateResources() {
    const updateConfirm = utils.imageUtil.findImageInCapture('login/update_resources_confirm.png')
    if (updateConfirm) {
        clickPos(updateConfirm)
    }
}

function updateResvision() {
    const updateConfirm = utils.imageUtil.findImageInCapture('login/update_revision_confirm.png')
    if (updateConfirm) {
        clickPos(updateConfirm)
    }
}

function skipNotice() {
    const noticeClosePos = utils.imageUtil.findImageInCapture('login/close.png')
    if (noticeClosePos) {
        clickPos(noticeClosePos)
    }
}

function quickGame(quickGame) {
    const protocol = utils.imageUtil.findImageInCapture('login/user_protocol.png')
    if (protocol) {
        clickPos(protocol)
        clickPos(quickGame)
    }
    const quickGameStart = utils.imageUtil.findImageInCapture('login/quick_game_start.png')
    if (quickGameStart) {
        clickPos(quickGameStart)
    }
}

function realNameAuthentication() {
    const accounts = utils.fileUtil.openFile('account.txt')
    let accountsArr = accounts.readlines()
    const namePos = utils.imageUtil.findImageInCapture('login/name.png')
    if (namePos) {
        let i = 0
        for (;;) {
            let realNameAuth = utils.imageUtil.findImageInCapture('login/real_name_auth.png')
            if (realNameAuth) {
                let account = accountsArr[i].split(' ')
                clickPos({x: 1000, y: 432})
                sleep(500)
                emptyInput()
                sleep(500)
                Text(account[0])
                sleep(500)
                KeyCode(66)
                sleep(2500)
                emptyInput()
                sleep(500)
                Text(account[1])
                sleep(500)
                clickPos({x: 965, y: 620})
                sleep(500)
                i++
                sleep(2000)
            } else {
                break
            }
        }
    }
}

function startGame (changeArea) {
    const source = utils.imageUtil.captureCurrentScreen()
    const startGameProtocol = utils.imageUtil.findTemplateImgInSource(source, 'login/start_game_protocol.png')
    startGameProtocol && clickPos(startGameProtocol)
    const current = utils.imageUtil.findTemplateImgInSource(source, 'login/current_server.png')
    if (current) {
        clickPos({x: 773, y: 538})
    } else {
        clickPos(changeArea)
        sleep(2000)
        const firstArea = utils.imageUtil.findImageInCapture('login/first_area.png')
        if (firstArea) {
            clickPos(firstArea)
            sleep(2000)
            const firstServer = utils.imageUtil.findImageInCapture('login/first_server.png')
            if (firstServer) {
                clickPos(firstServer)
                sleep(2000)
                clickPos({x: 773, y: 538})
            }
        }
    }
}

function createUserAvatar(pos) {
    const userName = formatDateTime(new Date())
    clickPos({ x: 780, y: 363 })
    Text(userName)
    sleep(500)
    clickPos(pos)
    sleep(500)
    clickPos(pos)
}

function formatDateTime(date) {
    function padZero(num) {
        return num < 10 ? '0' + num : num;
    }

    var year = date.getFullYear();
    var month = padZero(date.getMonth() + 1);
    var day = padZero(date.getDate());
    var hours = padZero(date.getHours());
    var minutes = padZero(date.getMinutes());
    var seconds = padZero(date.getSeconds());

    return month + day + minutes + seconds;
}

function emptyInput() {
    for (let i = 0; i < 50; i++) {
        KeyCode(67)
    }
    sleep(200)
}

function addState(store, state) {
    let states = store.get('states')
    states.push(state)
    store.put('states', states)
}

function isStateNotExc(store, state) {
    let states = store.get('states')
    return states.findIndex(a => a == state) === -1
}

main()
